package luj.tool.jnproxyan.proxy.start.collect;

import luj.tool.jnproxyan.proxy.admin.AdminHttpHandler;
import luj.tool.jnproxyan.proxy.admin.AdminHttpMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class HttpHandleCollector {

  public interface Kit {

    AdminHttpMeta meta();

    AdminHttpHandler handler();
  }

  public List<Kit> collect() {
    return _metaList.stream()
        .map(this::makeKit)
        .collect(Collectors.toList());
  }

  private Kit makeKit(AdminHttpMeta meta) {
    Class<?> handlerClass = meta.getClass().getDeclaringClass();
    Object handler = _spring.getBean(handlerClass);

    return new Kit() {
      @Override
      public AdminHttpMeta meta() {
        return meta;
      }

      @Override
      public AdminHttpHandler handler() {
        return (AdminHttpHandler) handler;
      }
    };
  }

  @Autowired
  List<AdminHttpMeta> _metaList;

  @Autowired
  ApplicationContext _spring;
}
